package com.freshcity.page.home
{
	import com.freshcity.common.TimeBarBack;
	import com.freshcity.component.container.Component;
	import com.freshcity.core.Dispatcher;
	import com.freshcity.lib.event.DataEvent;
	import com.freshcity.lib.event.EventName;
	import com.freshcity.manager.EffectManager;
	import com.freshcity.utils.StringUtil;
	import com.greensock.TweenLite;
	
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	
	public class TimeBar extends Component
	{
		public var isTick:Boolean;
		public var callBackFun:Function;
		
		private var _totalTime:int;
		private var back:TimeBarBack;
		private var leftTime:int;
		private const TIME_DELAY:int = 1;
		
		public function TimeBar(parent:DisplayObjectContainer=null, xpos:Number=0, ypos:Number=0)
		{
			super(parent, xpos, ypos);
		}
		
		override protected function addChildren():void
		{
			super.addChildren();
			back = new TimeBarBack();
			addChild(back);
			
			back.timeValue.visible=false;
		}
		
		override public function destroy():void
		{
			super.destroy();
		}

		public function get data():int
		{
			return _totalTime;
		}

		public function set data(value:int):void
		{
			_totalTime = value;
			this.leftTime = value;
			this.isTick = true;
			this.show();
			onTick();
		}
		
		private function onTick():void
		{
			if(this.leftTime>=0){
				var t:int = back.timeRender.totalFrames;
				var j:int = int(this.leftTime/_totalTime*t);
				back.timeRender.gotoAndStop(j);
				
				var s:String = StringUtil.formatTime(this.leftTime)
				back.timeValue.text = "剩余时间 " + s;
				this.leftTime--;
				TweenLite.delayedCall(TIME_DELAY,onTick,null,true);
			}else{
				this.isTick = false;
				this.hide();
				callBackFun.call(null);
				callBackFun = null;
				Dispatcher.dispatchEvent(new DataEvent(EventName.FinishTimeTick));
			}
		}
		
		override public function hide(event:Event=null):void
		{
			this.visible = false;
			EffectManager.hideUIMask();
		}
		
		override public function show(event:Event=null):void
		{
			this.visible = true;
			this.x = (stage.stageWidth - back.width)/2;
			this.y = (stage.stageHeight - back.height)/2;
			EffectManager.addUIMask([],0);
		}
		
	}
}